package ru.timofeyco.justfeelbetter;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

import ru.timofeyco.justfeelbetter.db.JustFeelBetterDatabase;
import ru.timofeyco.justfeelbetter.model.DayResult;
import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.widget.TabHost;

public class MainActivity extends TabActivity {
	JustFeelBetterDatabase dbHelper;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        this.dbHelper = new JustFeelBetterDatabase(this);
        initializeDayResult();
                       
        Resources res = getResources();		// Resource object to get Drawables
        TabHost tabHost = getTabHost(); 	// The activity TabHost
        TabHost.TabSpec spec;  				// Reusable TabSpec for each tab        
        Intent intent;  					// Reusable Intent for each tab                

        // Create an Intent to launch an Activity for the tab (to be reused)
        intent = new Intent().setClass(this, DayActivity.class);

        // Initialize a TabSpec for each tab and add it to the TabHost
        spec = tabHost.newTabSpec("today").setIndicator(getString(R.string.today_caption),
                          res.getDrawable(R.drawable.ic_tab_today))
                      .setContent(intent);
        tabHost.addTab(spec);

        // Do the same for the other tabs
        intent = new Intent().setClass(this, MonthActivity.class);
        spec = tabHost.newTabSpec("month").setIndicator(getString(R.string.month_caption),
                          res.getDrawable(R.drawable.ic_tab_month))
                      .setContent(intent);
        tabHost.addTab(spec);

        intent = new Intent().setClass(this, EditTypesActivity.class);
        spec = tabHost.newTabSpec("drilltypes").setIndicator(getString(R.string.edittypes_caption),
                          res.getDrawable(R.drawable.ic_tab_edittypes))
                      .setContent(intent);
        tabHost.addTab(spec);       
        tabHost.setCurrentTab(0);
    }
    
    @Override
    protected void onResume() {
    	super.onResume();
    	
    	initializeDayResult();
    }

	private void initializeDayResult() {
		Date today = Calendar.getInstance().getTime();
		today = new Date(today.getYear(), today.getMonth(), today.getDate());
				
		DayResult dayResult = dbHelper.getDayResult(today);
		if (dayResult == null) {
			dayResult = new DayResult(today, 0);
			try {
				dbHelper.insertDayResult(dayResult);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}		
	}   
}